var _player;

function initPlayer()
{
  _player = new Player();
  _player.init();
}

function playAudio(clipFile, clipBegin, clipEnd, callback)
{
  _player.stop();
  _player.play_track(clipFile.path, clipBegin, clipEnd, callback);
}

function stopDAISYPlayback()
{
  _player.stop();
}

function pauseDAISYPlayback()
{
  _player.pauseOrResume();
}

// Create the audio player
function Player()
{
}

Player.prototype =
{
	// initialize the player
	init: function(playlist)
  {
		this.player = Components
      .classes["@XulMusic.org;Player;1"]
      .getService(Components.interfaces.xmIPlayer);
	},

  pauseOrResume: function()
  {
    if (this.player.track) {
      if (this.player.track.getState() ==
          Components.interfaces.xmITrack.PAUSED) {
        this.resume();
      } else if (this.player.track.getState() ==
          Components.interfaces.xmITrack.PLAYING) {
        this.pause();
      }
    }
  },

  pause: function()
  {
  },

  resume: function()
  {
  },

  // Start playing the track at the given URL
	play_track: function(path, begin, end, callback)
  {
		this.player.track = this.player.newTrack(path);
    begin = this.parse_time(begin);
    end = this.parse_time(end);
    this.player.track.setPosition(begin);
		this.player.play();
		this.endOfAudioAt(end - begin, callback);
    updateMenusPlaying();
	},

  // Parse a time expression of the form "npt=<number>s" and return a
  // millisecond length
  parse_time: function(nptstr)
  {
    var result = this.timeRe.exec(nptstr);
    var time = Math.round(parseFloat(result[1]) * 1000.0);
    dump(nptstr + " -> " + result[1] + " -> " + time + "\n");
    return time;
  },

	// stops current track
	stop: function()
  {
		if (this.progTimeout) {
			window.clearTimeout(this.progTimeout);
      dump("? (stopped)\n");
			this.progTimeout = null;
		}
		this.player.stop();
    updateMenusStopped();
	},

  // End audio playback after dur milliseconds, stop and call callback
  // function
  endOfAudioAt: function(dur, callback)
  {
    window.clearTimeout(this.progTimeout);
    var _this = this;
    this.progTimeout = window
      .setTimeout(function() { _this.stop(); callback(); }, dur);
  },

	player : null,
	track : null,
	progTimeout : 0,
  timeRe : /npt=(\d*\.?\d*)s/
};
